Day 10: Modules and Packages
Importing Modules
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
from random import randint, choice
print(randint(1, 100))
print(choice(["apple", "banana", "cherry"]))
Useful Standard Libraries
| Module | Purpose | Example |
|---|---|---|
math | Math functions | math.ceil(3.2) |
random | Random number generation | random.shuffle(lst) |
os | Operating system interface | os.getcwd() |
sys | System parameters | sys.argv |
collections | Specialized containers | Counter, defaultdict |
itertools | Iterator tools | product, permutations |
User-Defined Modules
You can create a utils.py file and use it as a module.
# utils.py
def add(a, b):
return a + b
PI = 3.14159
# main.py
from utils import add, PI
print(add(3, 5)) # 8
name == “main”
# calculator.py
def multiply(a, b):
return a * b
if __name__ == "__main__":
# Runs only when executed directly
result = multiply(3, 4)
print(f"Result: {result}")
Package Structure
mypackage/
├── __init__.py
├── math_utils.py
└── string_utils.py
from mypackage.math_utils import add
from mypackage import string_utils
Today’s Exercises
- Use
collections.Counterto print the 3 most frequent characters in a string. - Use
itertools.combinationsto generate 5 lottery number combinations. - Separate calculator functions into a module and import them from a main file.